/*
 * @Author: your name
 * @Date: 2021-08-12 09:07:53
 * @LastEditTime: 2021-11-17 14:16:21
 * @LastEditors: Please set LastEditors
 * @Description: 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 * @FilePath: \li-yuwei\demo-work\src\store\index.js
 */
import Vue from "vue";
import Vuex from "vuex";
import createPersistedState from "vuex-persistedstate";
import Cookie from "js-cookie";
// vuex持久化
import api from "../api";
//路由实例
import router from "../router";
//路由表
import routers from "../router/routes";
//筛选路由表方法
import filterRouter from "../utils/filterRouter";
Vue.use(Vuex);
//自动引入modules下的文件
// const modulesFiles = require.context("./modules", true, /\.js$/);
// const modules = modulesFiles.keys().reduce((modules, modulePath) => {
//     const moduleName = modulePath.replace(/^\.\/(.*)\.\w+$/, "$1");
//     const value = modulesFiles(modulePath);
//     modules[moduleName] = value.default;
//     return modules;
// }, {});

const store = new Vuex.Store({
    state: {
        user: {},
        Routers: [],
        refreshNum: 0,
    },
    mutations: {
        set_state(state, data) {
            state[data.key] = data.data;
        },
        addRefNum(state) {
            state.refreshNum = state.refreshNum + 1;
        },
        resetRefreshNum(state) {
            state.refreshNum = 0;
        },
    },
    actions: {
        async Login({ commit, dispatch }, payload) {
            //拿到账号密码
            const { username, password } = payload;
            //请求登录接口
            const res = await api.login({ username, password });
            //判断res类型 --->接口返回成功与失败格式不同
            if (typeof res.data !== "string") {
                //设置cookie
                Cookie.set("token", res.data.token);
                //本地存储用户信息
                localStorage.setItem("userData", JSON.stringify(res.data.userData));
                //调用getRouters方法(鉴权路由)
                dispatch("getRouters", res.data.userData.identity);
                //设置user信息
                commit("set_state", { key: "user", data: res.data.user });
            } else {
                alert(res.data);
            }
        },
        async getRouters({ commit }, auth) {
            //筛选路由
            let res = filterRouter(routers, auth);
            //循环添加路由
            res.forEach((item) => {
                router.addRoute(item);
            });
            //跳转
            router.push("/home");
            //设置Routers
            commit("set_state", { key: "Routers", data: res });
        },
    },
    modules: {},
    plugins: [
        createPersistedState({
            storage: window.sessionStorage,
            reducer(state) {
                return {
                    // 只储存state中的user
                    user: state.user,
                };
            },
        }),
    ],
});

export default store;